package com.ukefu.webim.util.weixin.handler;

import java.util.Collection;
import java.util.Map;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.UKTools;
import com.ukefu.util.client.UserClient;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.WeiXinUserRepository;
import com.ukefu.webim.service.repository.WxMpEventRepository;
import com.ukefu.webim.util.UKWeiXinTools;
import com.ukefu.webim.web.model.Instruction;
import com.ukefu.webim.web.model.WeiXinUser;
import com.ukefu.webim.web.model.WxMpEvent;

/**
 * @author Binary Wang
 */
@Component
public class SubscribeHandler extends AbstractHandler {

	@Autowired
	private WxMpEventRepository wxMpEventRes ;
	
	@Autowired
	private WeiXinUserRepository weiXinUserRes ;
	
    @SuppressWarnings("unchecked")
	@Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
            Map<String, Object> context, WxMpService weixinService,
            WxSessionManager sessionManager) throws WxErrorException {
		String key = wxMessage.getFromUser();
		if (context != null && StringUtils.isNotBlank((String)context.get("snsid"))) {
			key = key + "_" + context.get("snsid");
		}
    	WxMpXmlOutMessage out = null ;
    	WeiXinUser user = (WeiXinUser) UserClient.getUserClientMap().get(key) ;
    	if(user!=null){
    		WxMpEvent event = new WxMpEvent() ;
    		event.setFromuser(user.getOpenid());
    		event.setAppid(user.getSnsid());
    		event.setSnsid(user.getSnsid());
    		event.setChannel(UKDataContext.ChannelTypeEnum.WEIXIN.toString());
    		event.setCountry(user.getCountry());
    		event.setProvince(user.getProvince());
    		event.setCity(user.getCity());
    		event.setCreater(user.getOpenid());
    		event.setOrgi(user.getOrgi());
    		event.setUsername(user.getNickname());
    		event.setEvent(UKDataContext.EventTypeEnum.SUB.toString());
    		wxMpEventRes.save(event) ;
    		
    		user.setSubscribe(true);
    		weiXinUserRes.save(user) ;
    		
    		String topic = UKTools.getTopic(user.getSnsid(), wxMessage.getMsgType(), wxMessage.getEvent(), wxMessage.getEventKey(),wxMessage.getContent()) ;
    		Collection<Instruction> insList = (Collection<Instruction>) CacheHelper.getIMRCacheBean().getCacheObject(topic, user.getOrgi());
    		if(insList!=null && insList.size()>0){
    			for(Instruction ins : insList){
    				try {
						out = UKWeiXinTools.processInstruction(ins, user, wxMessage, weixinService,false) ;
					} catch (Exception e) {
						e.printStackTrace();
					}
    			}
    		}
    	}

        return out;
    }
}
